
//  SpotTaskViewController.m
//  DigiOps
//
//  Created by app on 2018/7/26.
//  Copyright © 2018年 俞渊华. All rights reserved.
//

#import "SpotTaskViewController.h"
#import "SpotViewCell.h"

#import "WBPopMenuModel.h"
#import "WBPopMenuSingleton.h"
#import "WBPopMenuView.h"
#import "XTAlertViewController.h"
#import "contentListSpot.h"
#import "SopTextViewController.h"
#import "SopAddPicViewController.h"
#import "HomeViewController.h"
#import "pictureData.h"

@interface SpotTaskViewController ()
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *scoreArray;
@property(nonatomic, strong)NSMutableArray *titleArray;
@property(nonatomic,strong)NSString* spotComment;
@property(nonatomic,strong)NSString* spotPicture;
@property(nonatomic,assign)int rejectCount;
@property(nonatomic,assign)BOOL rejectStatus;
@property(nonatomic,assign)NSString* refuseRemark;

@property(nonatomic,assign)NSInteger execS;

@end

@implementation SpotTaskViewController
static SpotTaskViewController *stv = nil;

+ (instancetype)share {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        stv = [[self alloc] init];
    });
    return stv;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _rejectCount=1;
    [self.view addSubview:self.tableView];
    self.execS=self.model.executeState;
    
    //默认block方法：设置上拉加载更多
    CGRect labelFrame = CGRectMake(0.0, 0.0, SCREEN_WIDTH, 36.0);
    UILabel *label = [[UILabel alloc] initWithFrame:labelFrame];
    label.font = [UIFont boldSystemFontOfSize:18];
    label.numberOfLines = 2;
    label.backgroundColor = [UIColor clearColor];
    label.textAlignment = UITextAlignmentLeft;
        label.textColor = [UIColor whiteColor];
    //    label.shadowColor = [UIColor blackColor];
    //    label.shadowOffset = CGSizeMake(0.0, -1.0);
    label.lineBreakMode = UILineBreakModeMiddleTruncation;
    label.text=@"临时任务";
    self.navigationItem.titleView = label;
    
    //提交按钮
    UIView *rightButtonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 150, 50)];
    
    UIButton *mainAndSearchBtn = [[UIButton alloc] initWithFrame:CGRectMake(100, 0, 50, 50)];
    
    [rightButtonView addSubview:mainAndSearchBtn];
    
    [mainAndSearchBtn setImage:[UIImage imageNamed:@"overflow_icon"] forState:UIControlStateNormal];
    
    [mainAndSearchBtn addTarget:self action:@selector(clickEvent) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightCunstomButtonView = [[UIBarButtonItem alloc] initWithCustomView:rightButtonView];
    //已完成不显示按钮
    if (_model.executeState!=1){
        self.navigationItem.rightBarButtonItem = rightCunstomButtonView;
        if ([[UserInfo share].role.powerType isEqualToString:@"1"]) {
            if (_model.executeState==2&&![_model.count isEqualToString:@"2"]){
                self.navigationItem.rightBarButtonItem=nil;
            }
        }
    }
    //调本地存储
    NSArray * array = [WorkOrderModel findWhere:@[@"uuid",@"=",_model.uuid]];
    if (array.count>0) {
        _model=(WorkOrderModel*)array[0];
        
        [self.tableView reloadData];
    }
    
    //返回
    self.navigationItem.hidesBackButton = YES;
    UIImage *image = [UIImage imageNamed:@"Back"];
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 0, 30, 44);
    backButton.imageEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    [backButton setImage:image forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftItemsSupplementBackButton = YES;
}
-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.scoreArray=[NSMutableArray new];
    self.titleArray=[NSMutableArray new];

    self.scoreArray=@[@"1.站点",@"2.优先级",@"3.执行人",@"4.建议开始时间",@"5.备注事项",@"6.保安人员备注",@"7.拍摄照片"];
//    self.titleArray=@[@"ADEN HQ",@"高",@"陈保安",@"30-7-2018",@"",@"",@""];
    //从model中取临时任务详情
    [self.titleArray addObject:_model.siteName];
    if (_model.priority==0) {
        [self.titleArray addObject:@"普通"];
    }
    else if (_model.priority==1)
    {
        [self.titleArray addObject:@"普通"];
    }
    else if (_model.priority==2)
    {
        [self.titleArray addObject:@"高"];
    }
    [self.titleArray addObject:_model.userName];
    //转换时间
    NSString*str=_model.proposalStartTime;
    
    NSTimeInterval time=[str doubleValue]/1000;
    
    [self.titleArray addObject:[self timestampSwitchTime:time andFormatter:@"YYYY-MM-dd HH:mm"]];
    [self.titleArray addObject:_model.workOrderRemark];
    [self.titleArray addObject:@"请在此处输入"];
    [self.titleArray addObject:@""];

    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
}

-(void)goBack
{
//    if (_model.executeState==1)
//        [self searchAticle];
//    else
//    {
        _model.spotCommnet=self.spotComment;
        _model.spotPicture=self.spotPicture;
        
        //    NSArray * array = [WorkOrderModel findWhere:@[@"uuid",@"=",_workModel.uuid]];
        //    if (array.count>0) {
        //        //删除sopuuid的pointmodel
        //        for (WorkOrderModel* pm in array) {
        //            [WorkOrderModel deleteWhere:@[@"uuid",@"=",_sopUuid]];
        //        }
        //    }
        [_model saveOrUpdateAsync:^(BOOL isSuccess) {
            
        }];

        [self.rt_navigationController popViewControllerAnimated:YES];
//    }
}
-(void)searchAticle{
    if (_model.executeState==1) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"不能提交" message:@"已提交的工单不能再次提交" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return;
    }
    _model.spotCommnet=self.spotComment;
    _model.spotPicture=self.spotPicture;
    BOOL a=!self.spotComment;
    BOOL b=!self.spotPicture;
    
    if (!self.spotComment&&!self.spotPicture)
    {
        if (_model.refuseRemark&&![_model.count isEqualToString:@"2"]) {
        }
        else{
//        [SVProgressHUD showInfoWithStatus:@"请填写备注或者拍照才能提交"];
        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"请填写备注或者拍照才能提交" withTime:1.0];

        return;
        }
    }
//    if (_model.executeState==0&&!self.spotPicture) {
//        [SVProgressHUD showInfoWithStatus:@"请填写备注或者拍照才能提交"];
//        return;
//    }
    if (self.block) {
        self.block(_model);
    };
    
//    NSArray * array = [WorkOrderModel findWhere:@[@"uuid",@"=",_workModel.uuid]];
//    if (array.count>0) {
//        //删除sopuuid的pointmodel
//        for (WorkOrderModel* pm in array) {
//            [WorkOrderModel deleteWhere:@[@"uuid",@"=",_sopUuid]];
//        }
//    }
        [_model saveOrUpdateAsync:^(BOOL isSuccess) {
            
        }];
    [self.rt_navigationController popViewControllerAnimated:YES];
}
-(void)clickEvent{
    if (self.execS==1) {
        return;
    }
    NSMutableArray *obj = [NSMutableArray array];
    
    for (NSInteger i = 0; i < [self titles].count; i++) {
        
        WBPopMenuModel * info = [WBPopMenuModel new];
        //        info.image = [self images][i];
        info.title = [self titles][i];
        [obj addObject:info];
    }
    
    [[WBPopMenuSingleton shareManager]showPopMenuSelecteWithFrame:150
                                                             item:obj
                                                           action:^(NSInteger index) {
                                                               NSLog(@"index:%ld",(long)index);
                                                               if ([[UserInfo share].role.powerType isEqualToString:@"1"]) {
                                                                   if (self.model.executeState==2)
                                                                   {
                                                                       if (index==0) {
                                                                           [MySingleton sharedMySingleton].reject=NO;
                                                                           
                                                                           [self searchAticle];
                                                                       }
                                                                   }
                                                                   else
                                                                   {

                                                               if (index==0) {
                                                                   [MySingleton sharedMySingleton].reject=YES;

                                                                   [self rejectSOP];
                                                               }
                                                               else
                                                               {
                                                                   [MySingleton sharedMySingleton].reject=NO;

                                                                   [self searchAticle];
                                                               }
                                                                   }
                                                               }
                                                               else
                                                               {
                                                                   if (index==0) {
                                                                       self.rejectStatus=YES;
                                                                       [MySingleton sharedMySingleton].reject=NO;

                                                                       [self submitSOP];
                                                                   }
                                                                   else
                                                                   {
                                                                       [MySingleton sharedMySingleton].reject=YES;

                                                                       [self rejectCloseSOP];
                                                                   }
                                                               }
                                                           }];
}
- (NSArray *) titles {
    if ([[UserInfo share].role.powerType isEqualToString:@"1"]) {
        if (self.model.executeState==2)
            return @[@"提交"];
        else
            return @[@"拒绝",@"提交"];
    }
    else
    {
        return @[@"强制执行",@"关闭任务"];
    }
}

- (NSArray *) images {
    return @[@"right_menu_QR@3x",
             @"right_menu_addFri@3x",
             @"right_menu_multichat@3x",
             @"right_menu_sendFile@3x",
             @"right_menu_facetoface@3x",
             @"right_menu_payMoney@3x"];
}
//gcd
-(void)gcdpost
{
    NSMutableArray* t=[NSMutableArray new];
    for (WorkOrderModel* m in self.orderCopy) {
        if (m.executeState==1&&m.workOrderType==3) {
            [t addObject:m];
        }
        if (m.executeState==2&&m.workOrderType==3) {
            if (m.rejectCount>0)//rejectCount==0应该不是刚提交过的，提交过的不为0,否则会提交（拒绝）不成功
                [t addObject:m];
        }
    }
    [MySingleton sharedMySingleton].totalCount=[MySingleton sharedMySingleton].totalCount+t.count;

    if (t.count==0) {
        return;
    }
    //    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    
    WorkOrderModel* m=(WorkOrderModel*)t[0];
    NSBlockOperation* op=[NSBlockOperation blockOperationWithBlock:^{
        [self gcdpostUI:m];
    }];
    for (int i=1; i<t.count; i++) {
        [op addExecutionBlock:^{
            [self gcdpostUI:(WorkOrderModel*)t[i]];
        }];
    }
    [op start];
}
-(void)gcdpostUI:(WorkOrderModel*)m{
    if (m.executeState==2) {
            [self postSubmitUIreject:m];
            return;
    }
    //时间问题
    NSDateFormatter *isoFormat = [[NSDateFormatter alloc] init];
    [isoFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
    
    
    NSDate*nowDate = [NSDate date];
    NSDate* theDate;
    
    
    theDate = nowDate;
    NSString* workStart=[self eightHour:theDate];
    m.workEndDate=workStart;
    if (!m.workStartDate) {
        m.workStartDate=workStart;
        //        dispatch_async(dispatch_get_main_queue(), ^{
        //            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"消息" message:@"请到任务详情重新提交" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        //            [alert show];
        //
        //        });
        //        return;
    }
    //
    contentListSpot* cl=[[contentListSpot alloc] init];
    cl.remark=m.spotCommnet;
    cl.picture=m.spotPicture;
    if ([self getDuplicateSubStrCountInCompleteStr:cl.picture withSubStr:@"-"]>2) {
        NSArray* pic=[pictureData findWhere:@[@"picuuid",@"=",cl.picture]];
        if (pic.count>0) {
            pictureData* pd=[pic objectAtIndex:0];
            if (pd.picurl) {
                cl.picture=pd.picurl;
            }
            NSMutableString* uu=[NSMutableString new];
            if (pd.multi.count>1) {
                for (int i=0; i<pd.multi.count; i++) {
                    NSArray* pics=[pictureData findWhere:@[@"picuuid",@"=",[pd.multi objectForKey:[NSString stringWithFormat:@"%i",i]]]];
                    if (pics.count>0) {
                        pictureData* pds=[pics objectAtIndex:0];
                        
                        [uu appendString:pds.picurl];
                        if (i!=pd.multi.count)
                            [uu appendString:@","];
                    }
                    
                }
                if ([uu hasSuffix:@","]) {
                    uu=[self removeLastOneChar:uu];
                }
                cl.picture=uu;
            }
        }
    }
    //如果二选一为空
    if (!cl.remark) {
        cl.remark=@"";
    }
    if (!cl.picture) {
        cl.picture=@"";
    }
    //    UserSites* s=[UserSites mj_objectWithKeyValues:[UserInfo share].sites[0]];
    NSMutableArray* content=[NSMutableArray new];
    [content addObject:cl];
    NSArray *dictArray = [contentListSpot mj_keyValuesArrayWithObjectArray:content];
    
    NSDictionary *params = @{
                             @"orderUuid" : m.uuid,
                             @"workOrderType" : @(m.workOrderType),
                             @"workOrderRemark" : m.workOrderRemark,
                             @"executeState" : @1,
                             @"workStartDate" : m.workStartDate,
                             @"workEndDate" : m.workEndDate,
                             @"contentList" : cl.mj_JSONString
                             
                             };
    NSLog(@"");
    MJExtensionLog(@"%@", params);
    MJExtensionLog(@"%@", dictArray.mj_JSONString);
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    });
    [HttpTool post:@"digiops/app/workOrder/InsertWorkOrderData" params:params success:^(id responseObj) {

        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        });
//        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"提交成功" withTime:1.0];
        [WorkOrderModel deleteWhere:@[@"uuid",@"=",m.uuid] ];
        [MySingleton sharedMySingleton].succCount++;

    } failure:^(NSError *error) {
        [MySingleton sharedMySingleton].nosuccCount++;

        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        });
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        
    }];
}

-(void)submitSOP
{
    if (![MySingleton sharedMySingleton].network) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"友情提醒" message:@"请检查网络状态" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return;
    }
    [self postUI];
}
-(void)postUI{//强制执行

    contentListSpot* cl=[[contentListSpot alloc] init];
    cl.remark=self.spotComment;
    cl.picture=self.spotPicture;
//    UserSites* s=[UserSites mj_objectWithKeyValues:[UserInfo share].sites[0]];
    NSMutableArray* content=[NSMutableArray new];
    [content addObject:cl];
    NSArray *dictArray = [contentListSpot mj_keyValuesArrayWithObjectArray:content];

    NSDictionary *params = @{
                             @"orderUuid" : _model.uuid,
                             @"workOrderType" : @(_model.workOrderType),
                             @"workOrderRemark" : _model.workOrderRemark,
                             @"executeState" : @1,
                             @"contentList" : cl.mj_JSONString

                             };
    if (self.rejectStatus) {
        params = @{
                   @"orderUuid" : _model.uuid,
                   @"workOrderType" : @(_model.workOrderType),
                   @"workOrderRemark" : _model.workOrderRemark,
                   @"executeState" : @1,
                   @"count" : @1,
                   @"contentList" : cl.mj_JSONString
                   
                   };
    }
    NSLog(@"");
    MJExtensionLog(@"%@", params);
    MJExtensionLog(@"%@", dictArray.mj_JSONString);
    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    [HttpTool post:@"digiops/app/workOrder/InsertWorkOrderData" params:params success:^(id responseObj) {

        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"提交成功" withTime:1.0];
        _model.executeState=[@"2" integerValue];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.rt_navigationController popViewControllerAnimated:YES];
        });
//        if (self.blockReject) {
//            self.blockReject();
//        }
        if (self.blockRejectSpot) {
            self.blockRejectSpot();
        }
        [WorkOrderModel deleteWhere:@[@"uuid",@"=",_model.uuid] ];
        [MySingleton sharedMySingleton].succCount++;

    } failure:^(NSError *error) {
        [MySingleton sharedMySingleton].nosuccCount++;

        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.rt_navigationController popViewControllerAnimated:YES];
        });
    }];
    self.rejectStatus=NO;
}
-(void)rejectSOP
{
    //临时任务不能拒绝两次
    if ([self.model.count isEqualToString:@"2"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"消息" message:@"不能拒绝" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
    else{
    XTAlertViewController *xtAlert = [[XTAlertViewController alloc] init];
    [xtAlert showViewWithImage:nil imageHeight:0 title:@"拒绝工单" btnTitles:@[@"取消", @"确认"] des:@"确认拒绝工单" style:AlertDefault fromVC:self];
    xtAlert.delegate=self;
    }
}
-(void)rejectCloseSOP
{
    if (![MySingleton sharedMySingleton].network) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"友情提醒" message:@"请检查网络状态" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return;
    }

//        XTAlertViewController *xtAlert = [[XTAlertViewController alloc] init];
//        [xtAlert showViewWithImage:nil imageHeight:0 title:@"确认关闭" btnTitles:@[@"取消", @"确认"] des:@"确认关闭工单" style:AlertDefault fromVC:self];
//        xtAlert.delegate=self;
    [MySingleton sharedMySingleton].refuseRemark=@"";
    self.refuseRemark=@"";
    _model.rejectCount=_rejectCount;//关闭工单也要计数
    _model.closeStatus=YES;
    [self postCloseEvent];
}
#pragma mark -
- (void)xt_alertViewControllerClickIndex:(NSInteger)buttonIndex remark:(NSString *)rem
{
    [MySingleton sharedMySingleton].refuseRemark=rem;
    self.refuseRemark=rem;
    switch (buttonIndex) {
        case 0:
            NSLog(@"0");
            NSLog(@"Cancel");
            break;
        case 1:
            NSLog(@"1");
            NSLog(@"Determine");
            _model.refuseRemark=rem;
            _model.rejectCount=_rejectCount;//拒绝计数
            [self postSubmitUIrejectEvent];
            break;
        case 2:
            NSLog(@"2");
            NSLog(@"summerxx");
            break;
        default:
            break;
    }
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([[UserInfo share].role.powerType isEqualToString:@"1"])
        return self.scoreArray.count;
    else{
        if (_model.refuseRemark) {
            return self.scoreArray.count-1;
        }
        else
            return self.scoreArray.count-2;
    }
//    return 10;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    SpotViewCell* cell=[SpotViewCell cellWithTableView:tableView];
    cell.spotTitle.text=[self.scoreArray objectAtIndex:indexPath.row];
    cell.spotContent.text=[self.titleArray objectAtIndex:indexPath.row];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
//    cell.textLabel.textAlignment = NSTextAlignmentCenter;//文字居中
    //    cell.model=[RouteModel new];
    if(indexPath.row==5){
        cell.spotContent.textAlignment=UITextAlignmentLeft;
        if (_model.spotCommnet) {
            cell.spotContent.text=_model.spotCommnet;
            self.spotComment=_model.spotCommnet;
        }
        if (self.spotComment) {
            cell.spotContent.text=self.spotComment;
        }
        if ([cell.spotContent.text isEqualToString:@"请在此处输入"]) {
            [cell.spotContent setTextColor:[UIColor lightGrayColor]];
        }
        else
            [cell.spotContent setTextColor:[UIColor blackColor]];

        //拒绝理由在这里
        if (_model.refuseRemark&&![_model.count isEqualToString:@"2"]) {
            if (![[UserInfo share].role.powerType isEqualToString:@"1"]){

            cell.spotTitle.text=@"6.拒绝理由";
            cell.spotContent.text=_model.refuseRemark;
            }
            return cell;
        }
        UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureRecognizer)];
        [cell addGestureRecognizer:tapGesture];
    }
    if (indexPath.row==6) {
        cell.spotPhoto.hidden=NO;
        if (_model.spotPicture) {
            [cell.spotPhoto setImage:[UIImage imageNamed:@"ic_photo_camera_withimage"]];
            self.spotPicture=_model.spotPicture;
        }
        if (self.spotPicture) {
            [cell.spotPhoto setImage:[UIImage imageNamed:@"ic_photo_camera_withimage"]];
        }
        UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureRecognizer1)];
        [cell addGestureRecognizer:tapGesture];
    }
    return cell;
}
-(void)tapGestureRecognizer
{
    SopTextViewController * detailVC = [[SopTextViewController alloc]init];
    //        detailVC.model = self.aticleArray[indexPath.row];
    if (_model.spotCommnet) {
        detailVC.saveText=_model.spotCommnet;
    }
    [self.rt_navigationController pushViewController:detailVC animated:YES];
    detailVC.block = ^(NSString *txt) {
        if ([txt isEqualToString:@""]) {
            self.spotComment=nil;
            [self.tableView reloadData];
        }
        else
        {
        self.spotComment=txt;
        [self.tableView reloadData];
        }
        _model.spotCommnet=self.spotComment;
//        cell.spotContent.text=txt;
//        self.commentTxt=txt;
    };
}
-(void)tapGestureRecognizer1
{
    SopAddPicViewController* detailVC = [[SopAddPicViewController alloc]init];
    //    detailVC.model = self.aticleArray[indexPath.row];
    detailVC.label=@"临时任务";
    NSMutableArray* pic=[NSMutableArray new];
    if (_model.spotPicture) {
        [pic addObject:_model.spotPicture];
        detailVC.scoreArray=[pic mutableCopy];
    }
    detailVC.blockPicurl = ^(NSString *picurl) {
        if (picurl.length>0) {

        self.spotPicture=picurl;
        [self.tableView reloadData];
        _model.spotPicture=self.spotPicture;
        }
    };
    [self.rt_navigationController pushViewController:detailVC animated:YES];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //    AticleModel * model = self.aticleArray[indexPath.row];
    //    if (model.ViewType == 1) {
    //        return [HomeBaseCell heightWithModel:model];
    //
    //    }else if (model.ViewType == 2) {
    //        return [HomeOneImageCell heightWithModel:model];
    //
    //    }else if (model.ViewType == 3){
    //        return [NewsMoreImageCell heightWithModel:model];0
    //    }else if (model.ViewType == 4){
    //        return [HomeOneImageCell heightWithModel:model];
    //    }
    return 130;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    /*
     NewsDetailViewController * detailVC = [[NewsDetailViewController alloc]init];
     detailVC.model = self.aticleArray[indexPath.row];
     [self.rt_navigationController pushViewController:detailVC animated:YES];
     */
    //    DetailViewController * detailVC = [[DetailViewController alloc]init];
    //    //    detailVC.model = self.aticleArray[indexPath.row];
    //    [self.rt_navigationController pushViewController:detailVC animated:YES];
}


- (UITableView *)tableView{
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
//        tableView.separatorColor=[UIColor clearColor];
        tableView.tableFooterView = [UIView new];
        UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
        view.backgroundColor = XMColor(241, 245, 247);
        UILabel* titleLabel = [[UILabel alloc]init];
        titleLabel.font = [UIFont xm_medium:17.0];
        titleLabel.numberOfLines = 1;
        titleLabel.textColor = [UIColor xm_jetblackColor];
        titleLabel.text=@"临时任务工单";
        
        [view addSubview:titleLabel];
        tableView.tableHeaderView=view;
        
        UIView * viewFoot = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 70)];
        viewFoot.backgroundColor = [UIColor whiteColor];
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        //        button.frame = CGRectMake(40, 100, SCREEN_WIDTH- 80, 30);
        button.backgroundColor = DGColor;
        [button setTitle:@"提交" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(submitRoute) forControlEvents:UIControlEventTouchUpInside];
        [viewFoot addSubview:button];
//                tableView.tableFooterView=viewFoot;
        //        [button setImage:[UIImage imageNamed:@"image"] forState:UIControlStateNormal];
        //        [button setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        //        [button setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(view).offset(18);
            make.left.equalTo(view.mas_left).offset(20);
        }];
        
//        [button mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.center.equalTo(viewFoot).offset(0);
//            //            make.top.equalTo(view).offset(5);
//            make.width.mas_equalTo(SCREEN_WIDTH-80);
//            make.height.mas_equalTo(50);
//            //            make.left.equalTo(view.mas_left).offset(20);
//        }];
        _tableView = tableView;
    }
    return _tableView;
}
-(void)submitRoute
{
    
}
-(void)postSubmitUIrejectEvent
{
    if ([self.refuseRemark isEqualToString:@""]&&[[UserInfo share].role.powerType isEqualToString:@"1"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"消息" message:@"请填写拒绝原因" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return;
    }
    if (self.block) {
        self.block(_model);
    };
    
    //    NSArray * array = [WorkOrderModel findWhere:@[@"uuid",@"=",_workModel.uuid]];
    //    if (array.count>0) {
    //        //删除sopuuid的pointmodel
    //        for (WorkOrderModel* pm in array) {
    //            [WorkOrderModel deleteWhere:@[@"uuid",@"=",_sopUuid]];
    //        }
    //    }
    [_model saveOrUpdateAsync:^(BOOL isSuccess) {
        
    }];
    [self.rt_navigationController popViewControllerAnimated:YES];

}
-(void)postCloseEvent
{
    if (self.block) {
        self.block(_model);
    };
    
    //    NSArray * array = [WorkOrderModel findWhere:@[@"uuid",@"=",_workModel.uuid]];
    //    if (array.count>0) {
    //        //删除sopuuid的pointmodel
    //        for (WorkOrderModel* pm in array) {
    //            [WorkOrderModel deleteWhere:@[@"uuid",@"=",_sopUuid]];
    //        }
    //    }
    [_model saveOrUpdateAsync:^(BOOL isSuccess) {
        
    }];
    [self postSubmitUIreject:_model];    
}
-(void)postSubmitUIreject:(WorkOrderModel*)m{
    
    contentListSpot* cl=[[contentListSpot alloc] init];
    cl.remark=self.spotComment;
    cl.picture=self.spotPicture;
    //    UserSites* s=[UserSites mj_objectWithKeyValues:[UserInfo share].sites[0]];
    NSMutableArray* content=[NSMutableArray new];
    [content addObject:cl];
    NSArray *dictArray = [contentListSpot mj_keyValuesArrayWithObjectArray:content];
    if (!self.refuseRemark) {
        self.refuseRemark=[MySingleton sharedMySingleton].refuseRemark;
    }
    if (!m.refuseRemark) {//为了不崩/////
        m.refuseRemark=@"";
    }
    NSDictionary *params = @{
                             @"orderUuid" : m.uuid,
                             @"workOrderType" : @(m.workOrderType),
                             @"workOrderRemark" : m.workOrderRemark,
                             @"executeState" : @2,
                             @"count" : @(m.rejectCount),
                             @"refuseRemark" : m.refuseRemark
                             
                             };

    NSLog(@"");
    MJExtensionLog(@"%@", params);
    MJExtensionLog(@"%@", dictArray.mj_JSONString);
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    });
    [HttpTool post:@"digiops/app/workOrder/InsertWorkOrderData" params:params success:^(id responseObj) {

        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        });
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"提交成功" withTime:1.0];
        _rejectCount++;
//        HomeViewController * homeVC = [[HomeViewController alloc]init];
//        RTRootNavigationController *nav = [[RTRootNavigationController alloc] initWithRootViewController:homeVC];
//        // 添加为子控制器
//        nav.title = @"任务箱";
//        [UIApplication sharedApplication].delegate.window.rootViewController=nav;
//        if (self.blockReject) {
//            self.blockReject();
//        }
        _model.executeState=[@"2" integerValue];
        [WorkOrderModel deleteWhere:@[@"uuid",@"=",m.uuid] ];
        if (m.closeStatus) {//关闭工单回调刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.rt_navigationController popViewControllerAnimated:YES];
            });
            if (self.blockRejectSpot) {
                self.blockRejectSpot();
            }
        }
        [MySingleton sharedMySingleton].succCount++;


    } failure:^(NSError *error) {
        [MySingleton sharedMySingleton].nosuccCount++;

        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        [self.rt_navigationController popViewControllerAnimated:YES];

    }];
}
#pragma mark - 将某个时间戳转化成 时间

-(NSString *)timestampSwitchTime:(NSInteger)timestamp andFormatter:(NSString *)format{
    
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:format]; // （@"YYYY-MM-dd hh:mm:ss"）----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:timestamp];
    
    NSLog(@"1296035591  = %@",confromTimesp);
    
    
    
    NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
    
    
    
    //NSLog(@"&&&&&&&confromTimespStr = : %@",confromTimespStr);
    
    
    
    return confromTimespStr;
    
}
@end
